package com.zhixin.weChat.itChat;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;

/**
 * 
 * @author 致心
 * @date 2019年9月29日 上午10:39:03
 */
@SuppressWarnings("deprecation")
public class SendMessageToFri implements IMsgHandlerFace {

	private static final Logger log = LoggerFactory.getLogger(SendMessageToFri.class);
	private final String URL = "https://api.ownthink.com/bot?appid=64b396a615bf8"
			+ "2a66e38174ae4fad0e8&userid=BZ8FCrxL&spoken=";//这是我申请的思知机器人的api调用

	@Override
	public String textMsgHandle(BaseMsg msg) {
		log.info("textMsgHandle");
		String result = null;
		String fromUserName = msg.getFromUserName();
		log.info("消息内容：" + msg.getText());
		log.info("消息id：" + msg.getMsgId());
		if (this.CanReturnMessage(fromUserName)) {// 接入机器人自动回复
			String spoken = msg.getText();
			log.info("textMsgHandle：" + spoken);
			result = this.robotReturnMessage(spoken);
		} else if (msg.getToUserName().equals("filehelper")) {// 使用指令控制
			if (msg.getText().equals("命令提示")) {
				this.commandTip();
			} else if (msg.getText().contains("命令添加回复的人")) {
				this.addRetuenName(msg.getText());
			} else if (msg.getText().contains("命令修改发送天气的城市")) {
				this.alterCity(msg.getText());
			} else if (msg.getText().contains("命令修改定时任务发送的对象")) {
				this.alterTimeUserName(msg.getText());
			} else if (msg.getText().contains("命令移除回复的人")) {
				this.removeReturnName(msg.getText());
			} else if (msg.getText().contains("命令天气立即发送一次")) {
				this.timeReturnUserName();
			} else if (msg.getText().contains("命令天气参数信息")) {
				this.weatherMessageParam();
			} else if (msg.getText().contains("命令自动回复的人")) {
				this.robotReturnUser();
			} else if (msg.getText().startsWith("命令")) {
				MessageTools.sendMsgById("没有这条命令", "filehelper");
			}
		}
		return result;
	}

	@Override
	public String picMsgHandle(BaseMsg msg) {
		log.info("picMsgHandle");
//		String fileName = msg.getMsgId();// 这里使用收到图片的时间作为文件名
//		String picPath = System.getProperty("user.dir")+File.separator+"src"+File.separator+"mytest"+File.separator+fileName + ".jpg"; // 调用此方法来保存图片
//		DownloadTools.getDownloadFn(msg, MsgTypeEnum.PIC.getType(), picPath); // 保存图片的路径
		String result = null;
		String fromUserName = msg.getFromUserName();
		if (this.CanReturnMessage(fromUserName)) {// 接入机器人自动回复
			String spoken = null;
			String pattern = "[a-zA-z]+://[^\\s]+/";
			Matcher matcher = Pattern.compile(pattern).matcher(msg.getContent());
			if (matcher.find()) {
				spoken = matcher.group();
			}
			result = this.robotReturnMessage(spoken);
		}
		return result;
	}

	@Override
	public String voiceMsgHandle(BaseMsg msg) {
		// TODO Auto-generated method stub
		log.info("voiceMsgHandle");
		return null;
	}

	@Override
	public String viedoMsgHandle(BaseMsg msg) {
		// TODO Auto-generated method stub
		log.info("viedoMsgHandle");
		return null;
	}

	@Override
	public String nameCardMsgHandle(BaseMsg msg) {
		// TODO Auto-generated method stub
		log.info("nameCardMsgHandle");
		return null;
	}

	@Override
	public void sysMsgHandle(BaseMsg msg) {
		// TODO Auto-generated method stub
		log.info("sysMsgHandle");
	}

	@Override
	public String verifyAddFriendMsgHandle(BaseMsg msg) {
		// TODO Auto-generated method stub
		log.info("verifyAddFriendMsgHandle");
		return null;
	}

	@Override
	public String mediaMsgHandle(BaseMsg msg) {
		// TODO Auto-generated method stub
		log.info("mediaMsgHandle");
		return null;
	}

	@Override
	public void messageBack(BaseMsg msg) {
		// TODO Auto-generated method stub
		log.info("messageBack");
		log.info("撤回的消息id：" + msg.getMsgId());
		log.info("谁撤回：" + msg.getFromUserName());
	}

	/**
	 * NickName备注， RemarkName，网名，包括
	 * 
	 * @author 致心
	 * @date_time:2019年9月29日 上午11:46:52
	 */
	private String returnUserName(String NickName, String RemarkName) {
		String string = null;
		List<JSONObject> contactList = WechatTools.getContactList();
		for (JSONObject jsonObject : contactList) {
			if (jsonObject.get("NickName").toString().contains(NickName)) {
				if (jsonObject.get("RemarkName").toString().contains(RemarkName)) {
					string = jsonObject.get("UserName").toString();
					break;
				}
			}
		}
		return string;
	}

	/**
	 * 提示自动回复的对象<br/>
	 * 命令自动回复的人
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午9:10:11
	 */
	private void robotReturnUser() {
		String result = "自动回复的对象有：\n";
		String NickNameAndRemarkName = "";
		String[] split = null;
		for (String string : WxSaveDate.returnUserNames) {
			NickNameAndRemarkName = this.returnNickNameAndRemarkName(string);
			split = NickNameAndRemarkName.split(":");
			result += ("网名：" + split[0] + "   " + "备注名：" + split[1] + "\n");
		}
		MessageTools.sendMsgById(result, "filehelper");
	}

	/**
	 * 通过username返回网名和备注名<br/>
	 * 格式NickName:RemarkName<br/>
	 * 返回出去进行解析
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午8:45:25
	 */
	private String returnNickNameAndRemarkName(String username) {
		String result = null;
		List<JSONObject> contactList = WechatTools.getContactList();
		for (JSONObject jsonObject : contactList) {
			if (jsonObject.get("UserName").toString().contains(username)) {
				String NickName = jsonObject.get("NickName").toString();
				String RemarkName = jsonObject.get("RemarkName").toString();
				result = NickName + ":" + RemarkName;
				break;
			}
		}
		return result;
	}

	/**
	 *
	 * @author 致心
	 * @date_time:2019年10月3日 下午2:58:47
	 */
	private String robotReturnMessage(String spoken) {
		spoken = spoken.replaceAll(" ", "%20");
		String result = null;
		try {
			HttpClient digestHttpClient = this.sslFreeDefaultHttpClient();
			log.info("请求回复消息链接：" + this.URL + spoken);
			HttpGet httpGet = new HttpGet(this.URL + spoken);
			result = EntityUtils.toString(digestHttpClient.execute(httpGet).getEntity(), "UTF-8");
			JSONObject obj = JSON.parseObject(result);
			if (obj.getString("message").equals("success")) {
				obj = JSON.parseObject(obj.getJSONObject("data").toJSONString());
				obj = JSON.parseObject(obj.getJSONObject("info").toJSONString());
				result = obj.getString("text");
			} else {
				result = "你的机器人出问题了";
				log.info("你的机器人出问题了" + obj.getString("message"));
			}
			log.info("result" + obj.toJSONString());
		} catch (Exception e) {
			log.info("请求错误");
		}
		return result;
	}

	/**
	 * 判断是否自动回复消息
	 * 
	 * @author 致心
	 * @date_time:2019年9月29日 下午8:19:39
	 */
	private boolean CanReturnMessage(String fromUserName) {
		for (String string : WxSaveDate.returnUserNames) {
			if (fromUserName.equals(string)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * https不进行ssl验证
	 * 
	 * @author 致心
	 * @date_time:2019年9月29日 下午8:24:24
	 */
	private HttpClient sslFreeDefaultHttpClient()
			throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
		TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
		SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy,
				SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("https", 8443, sf));
		ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

		return new DefaultHttpClient(ccm);
	}

	/**
	 * 添加可以回复消息的人<br/>
	 * 命令添加回复的人:网名:备注名
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 上午9:46:14
	 */
	private void addRetuenName(String text) {
		String[] split = text.split(":");
		if (this.commandCheck(split, 3)) {
			String returnUserName = this.returnUserName(split[1], split[2]);
			if (returnUserName != null) {
				if (!this.theUserNameExists(returnUserName)) {
					WxSaveDate.returnUserNames.add(returnUserName);
					MessageTools.sendMsgById("添加成功", "filehelper");
				}
			} else {
				MessageTools.sendMsgById("好友列表中不存在" + split[2] + "用户", "filehelper");
			}
		}
	}

	/**
	 * 检测在returnUserNames是不是存在returnUserName
	 * 
	 * @author 致心
	 * @date_time:2019年10月10日 上午10:59:11
	 */
	private boolean theUserNameExists(String userName) {
		for (String user : WxSaveDate.returnUserNames) {
			if (user.equals(userName)) {
				MessageTools.sendMsgById("用户已经存在", "filehelper");
				return true;
			}
		}
		MessageTools.sendMsgById("用户不存在", "filehelper");
		return false;
	}

	/**
	 * 移除可以回复消息的人<br/>
	 * 命令移除回复的人:网名:备注名
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午1:54:22
	 */
	private void removeReturnName(String text) {
		String[] split = text.split(":");
		if (this.commandCheck(split, 3)) {
			String returnUserName = this.returnUserName(split[1], split[2]);
			if (returnUserName != null) {
				if (this.theUserNameExists(returnUserName)) {
					WxSaveDate.returnUserNames.remove(returnUserName);
					MessageTools.sendMsgById("移除成功", "filehelper");
				}
			} else {
				MessageTools.sendMsgById("好友列表中不存在" + split[2] + "用户", "filehelper");
			}
		}
	}

	/**
	 * 检查命令是不是符合格式，符合返回为true
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午1:29:03
	 */
	private boolean commandCheck(String[] split, int length) {
		if (split.length != length) {
			MessageTools.sendMsgById("命令格式有错", "filehelper");
			return false;
		} else {
			for (String string : split) {
				if (!this.isNotEmpty(string)) {
					MessageTools.sendMsgById("命令格式有错", "filehelper");
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 命令提示，发送命令提示4个字回复所有的命令方式使用方法
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 上午9:49:55
	 */
	private void commandTip() {
		String tip = "命令解释：网名和备注名只要文字包含就行，输入表情可能会出错\n" + "1、命令添加回复的人:网名:备注名\n" + "2、命令修改发送天气的城市:城市名字\n"
				+ "3、命令修改定时任务发送的对象:网名:备注名\n" + "4、命令移除回复的人:网名:备注名\n" + "5、命令天气立即发送一次\n" + "6、命令天气参数信息\n" + "7、命令自动回复的人";
		MessageTools.sendMsgById(tip, "filehelper");
	}

	/**
	 * 返回天气参数信息<br/>
	 * 命令天气参数信息
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午8:49:55
	 */
	private void weatherMessageParam() {
		String message = "天气信息是：\n";
		if (this.isNotEmpty(WxSaveDate.city)) {
			message += ("城市是：" + WxSaveDate.city + "\n");
		}
		if (this.isNotEmpty(WxSaveDate.timeUserName)) {
			String NickNameAndRemarkName = this.returnNickNameAndRemarkName(WxSaveDate.timeUserName);
			String[] split = NickNameAndRemarkName.split(":");
			message += ("发送的对象是：" + split[1] + "\n");
		}
		MessageTools.sendMsgById(message, "filehelper");
	}

	/**
	 * 修改发送天气的城市<br/>
	 * 命令修改发送天气的城市:城市名字
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午1:32:41
	 */
	private void alterCity(String text) {
		String[] split = text.split(":");
		if (this.commandCheck(split, 2)) {
			WxSaveDate.city = split[1];
			MessageTools.sendMsgById("修改成功", "filehelper");
		}
	}

	/**
	 * 修改定时任务发送的对象 <br/>
	 * 命令修改定时任务发送的对象:网名:备注名
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午1:35:31
	 */
	private void alterTimeUserName(String text) {
		// TODO Auto-generated method stub
		String[] split = text.split(":");
		if (this.commandCheck(split, 3)) {
			WxSaveDate.timeUserName = this.returnUserName(split[1], split[2]);
			MessageTools.sendMsgById("修改成功", "filehelper");
		}
	}

	/**
	 * 字符串有内容
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午1:59:45
	 */
	private boolean isNotEmpty(String string) {
		if (string != null && string != "") {
			return true;
		}
		return false;
	}

	/**
	 * 这是一个定时任务，提供给定时任务类调用，发送天气消息
	 * 
	 * @author 致心
	 * @date_time:2019年10月4日 下午1:23:09
	 */
	public void timeReturnUserName() {
		if (!this.isNotEmpty(WxSaveDate.city)) {
			MessageTools.sendMsgById("请指定城市", "filehelper");
			return;
		}
		if (!this.isNotEmpty(WxSaveDate.timeUserName)) {
			MessageTools.sendMsgById("请指定发送的对象", "filehelper");
			return;
		}
		String robotReturnMessage = this.robotReturnMessage(WxSaveDate.city + "天气");
		MessageTools.sendMsgById(robotReturnMessage, WxSaveDate.timeUserName);
	}

}
